// speech-service.ts

import { Injectable } from '@nestjs/common';
import WebSocket from 'ws';
import CryptoJS from 'crypto-js';
import { Response } from 'express';
import axios from 'axios';
@Injectable()
export class AppService {
  private socket: WebSocket;
  private session: string;

  // constructor() {
  //   this.connectToSpeechAPI();
  // }

  public connectToSpeechAPI(message: string, res: Response) {
    this.socket = new WebSocket(this.getWebsocketUrl());

    this.socket.on('open', () => {
      // 可以在连接成功后执行一些操作
      this.sendMessage(message);
    });

    this.socket.on('message', (e) => {
      // console.log('Received message from server:', e);
      console.log(JSON.parse(e));
      const result = JSON.parse(e);
      this.sendSseMessage(result, res);
      
      // 处理从服务器接收到的消息
    });

    this.socket.on('close', (code, reason) => {
      console.log(
        `WebSocket connection closed with code ${code} and reason ${reason}`,
      );
      // 可以尝试重新连接或执行其他操作
    });
  }
  sendSseMessage(result: any, res: Response) {
    res.write(`data: ${JSON.stringify(result)}\n\n`);
    if (result.header.status === 2) {
      res.end();
    }
  }
  getWebsocketUrl() {
    var apiKey = '43defad0482a56c7c4c7feda951941e5';
    var apiSecret = 'YzhkNGNmMGM4MzRlYWQwZTQ4OWU2ZDJk';
    var url = 'wss://spark-api.xf-yun.com/v3.1/chat';
    var host = 'aichat.xf-yun.com';
    var date = new Date().toUTCString();
    var algorithm = 'hmac-sha256';
    var headers = 'host date request-line';
    var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v3.1/chat HTTP/1.1`;
    var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
    var signature = CryptoJS.enc.Base64.stringify(signatureSha);
    var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    var authorization = btoa(authorizationOrigin);
    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
    return url;
  }

  getPersonUrl(
    tmpurl = 'https://vms.cn-huadong-1.xf-yun.com/v1/private/vms2d_start',
    line = '/v1/private/vms2d_start',
  ) {
    var apiKey = '803d79229e439e18814e05e4c7753f5a';
    var apiSecret = 'NDQzNjg2ZTlmMjkyOTU0NWUxOWE2ZGNl';
    var url = tmpurl;
    var host = 'vms.cn-huadong-1.xf-yun.com';
    var date = new Date().toUTCString();
    var algorithm = 'hmac-sha256';
    var headers = 'host date request-line';
    var signatureOrigin = `host: ${host}\ndate: ${date}\nPOST ${line} HTTP/1.1`;
    var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
    var signature = CryptoJS.enc.Base64.stringify(signatureSha);
    var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    var authorization = btoa(authorizationOrigin);
    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
    console.log(url);
    return url;
  }

  async startPerson() {
    const params = {
      header: {
        app_id: '57702c9b',
        uid: '',
      },
      parameter: {
        vmr: {
          stream: {
            protocol: 'rtmp',
          },
          avatar_id: '110017006',
          width: 1280,
          height: 720,
          transparent: 1,
          // isSsl: true,
          // maskRegion: '[0,154,1080,1472]',
          // moveH: 0,
          // moveV: 0,
          // scale: 1,
        },
      },
    };
    const res = await axios.request({
      url: this.getPersonUrl(),
      method: 'post',
      headers: { 'Content-Type': 'application/json' },
      data: JSON.stringify(params),
    });
    console.log(res);
    return 111;
  }

  async stopPerson() {
    const params = {
      header: {
        app_id: '57702c9b',
        uid: '',
        session:
          'xdF7sUElilEdfmAlfGFHu8h5EmHlgQAZgQAcfmIZhmRMgQv4hmWlfGF4tTIlilFkv7RbgVAciVwnh5BHwQWKhQBphmkpr4rLgVI5gQW8glF9',
      },
    };
    const res = await axios.request({
      url: this.getPersonUrl(
        'https://vms.cn-huadong-1.xf-yun.com/v1/private/vms2d_stop',
        '/v1/private/vms2d_stop',
      ),
      method: 'post',
      headers: { 'Content-Type': 'application/json' },
      data: JSON.stringify(params),
    });
    console.log(res);
    return 111;
  }

  sendMessage(message: string) {
    console.log(this.socket.readyState === this.socket.OPEN);
    if (this.socket.readyState === this.socket.OPEN) {
      var params = {
        header: {
          app_id: '925e4841',
          uid: 'fd3f47e4-d',
        },
        parameter: {
          chat: {
            domain: 'generalv3',
            temperature: 0.5,
            max_tokens: 1024,
          },
        },
        payload: {
          message: {
            text: [
              {
                role: 'user',
                content: message,
              },
            ],
          },
        },
      };
      this.socket.send(JSON.stringify(params));
    }
  }
}
